import 'dart:ffi';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:test01/okhttp_test/page/pages/okhttp_main.dart';
import 'package:test01/okhttp_test/pojo/attention_pojo.dart';
import 'package:test01/okhttp_test/util/request_http.dart';

void main() => runApp(
      MyApp(),
    );

class MyApp extends StatefulWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CanvasTestPage(),
    );
  }
}

class CanvasTestPage extends StatefulWidget {
  const CanvasTestPage({Key key}) : super(key: key);

  @override
  _CanvasTestPageState createState() => _CanvasTestPageState();
}

class _CanvasTestPageState extends State<CanvasTestPage> {
  ///控制器
  ScrollController scrollController = ScrollController();

  ///定义接受数据的对象
  GetMyWigets getMyWigets = GetMyWigets();

  ///定义获取的体重列表
  List<GetRecordLists> getRecordList = [];

  ///判断是否到了最后数据
  bool isLast = false;

  ///初始化Size长度
  var startSize;

  int mm;

  @override
  void initState() {
    super.initState();
    //调用接口
    getUserWeight();

    //初始化size长度
    startSize = ((MediaQuery.of(context).size.width - 53.5 - 21) / 5) *
        (getRecordList.length >= 5 ? getRecordList.length : 5);

    //监听滚动到底部
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        if (isLast) {
          print("==================后面没有数据拉==================");
        } else {
          //左拉加载更多
          getUserWeightRefresh();
        }
      }
    });
  }

  ///点击的范围
  Widget zz(
    int i,
  ) {
    var startX;
    startX = 224 -
        (((((224 / 5) * 5) - (224 / 5)) / 100) * (getRecordList[i].weight));
    return Stack(
      children: <Widget>[
        Container(
          width: ((MediaQuery.of(context).size.width - 50 - 18) / 5),
          // 下边框
          decoration: BoxDecoration(
            color:
                Colors.primaries[i % Colors.primaries.length].withOpacity(0.0),
          ),
          height: 300,
          // margin: EdgeInsets.only(left: 1),
        ),
        i == mm
            ? Container(
                width: 50,
                height: 20,
                alignment: Alignment.center,
                margin: EdgeInsets.only(
                    top: (startX > 224 ? startX + 12 : startX - 32),
                    left: i == (getRecordList.length - 1) ? 10 : 0),
                decoration: BoxDecoration(
                  border: Border.all(width: 0.5, color: Colors.red),
                ),
                child: Text(
                  "${getRecordList[i].weight}kg",
                  style: TextStyle(fontSize: 12),
                ),
              )
            : Container()
      ],
    );
  }

  ///调用用户记录体重的接口
  getUserWeight() async {
    getMyWigets = await getWeightRecords(
        interface: "/appuser/web/user/getWeightRecords", page: 1, size: 5);

    ///复制请求的页面
    getMyWigets.page = 1;
    if (getMyWigets != null) {
      getMyWigets.recordList.forEach((element) {
        getRecordList.add(element);
        setState(() {});
      });
    }
  }

  ///刷新的数据
  getUserWeightRefresh() async {
    int page = getMyWigets.page + 1;
    //定义数据列表为空
    GetMyWigets newGetMyWigets = GetMyWigets();
    newGetMyWigets = await getWeightRecords(
        interface: "/appuser/web/user/getWeightRecords", page: page, size: 5);
    //调取接口值
    if (newGetMyWigets != null) {
      //数组添加数据
      newGetMyWigets.recordList.forEach((element) {
        getRecordList.add(element);
      });
      getMyWigets = newGetMyWigets;
      getMyWigets.page = page;
      isLast = false;
      setState(() {});
    } else {
      isLast = true;
      setState(() {});
    }
  }

  ///单击画布的布局
  Widget MyChangeWidget() {
    return mm != null
        ? Container(
            child: CustomPaint(
              // size：当child为null时，代表默认绘制区域大小，如果有child则忽略此参数，画布尺寸则为child尺寸
              size: Size(startSize, 300),
              painter: MyChangeY(getRecordList, context, mm),
            ),
          )
        : Container();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        ///X轴
        Container(
          margin: EdgeInsets.only(left: 53.5 - 16),
          // color: Colors.white,
          child: CustomPaint(
            // size：当child为null时，代表默认绘制区域大小，如果有child则忽略此参数，画布尺寸则为child尺寸
            size: Size(MediaQuery.of(context).size.width - 32 - 21, 224),
            painter: MyPainterX(getRecordList),
          ),
        ),

        ///X轴以及轴的点
        Container(
          width: MediaQuery.of(context).size.width - 53.5 - 21 - 21,
          margin: EdgeInsets.only(left: 53.5 + 21),
          height: 268,
          alignment: Alignment.center,
          child: SingleChildScrollView(
              controller: scrollController,
              scrollDirection: Axis.horizontal,
              reverse: true,
              child: Container(
                width: startSize,
                height: 268,
                child: Stack(
                  children: <Widget>[
                    ///X轴画布
                    Container(
                      child: CustomPaint(
                        // size：当child为null时，代表默认绘制区域大小，如果有child则忽略此参数，画布尺寸则为child尺寸
                        size: Size(startSize, 300),
                        painter: MyPainterY(getRecordList, context, mm),
                      ),
                    ),

                    MyChangeWidget(),

                    ///X轴点击事件
                    Container(
                      height: 226,
                      child: ListView.builder(
                        physics: NeverScrollableScrollPhysics(),
                        scrollDirection: Axis.horizontal,
                        reverse: true,
                        itemBuilder: (BuildContext context, int i) {
                          return GestureDetector(
                            onTap: () {
                              mm = i;
                              setState(() {});
                            },
                            child: zz(i),
                          );
                        },
                        itemCount: getRecordList.length,
                      ),
                    ),
                  ],
                ),
              )),
        ),
      ],
    );
  }
}

//画布Y坐标轴
class MyPainterX extends CustomPainter {
  MyPainterX(this.getRecordLists);

  //获取接口数据
  List<GetRecordLists> getRecordLists;

  //最大体重值
  double maxWeight;

  zz() {
    maxWeight = 0.0;
    for (int i = 0; i < getRecordLists.length; i++) {
      if (maxWeight < getRecordLists[i].weight) {
        maxWeight = getRecordLists[i].weight;
      }
    }
  }

  @override
  void paint(Canvas canvas, Size size) {
    ///获取最大的体重数
    zz();

    ///床架画笔
    var paint = Paint()
      ..strokeWidth = 1
      ..isAntiAlias = true // 是否抗锯齿
      ..color = Color.fromRGBO(153, 153, 153, 1);

    ///创建背景虚线
    var max = size.width - 16; // size获取到宽度
    //虚线之间的宽度
    var dashWidth = 5;
    var dashSpace = 5;
    //虚线X轴的初始值
    double startX = 37.5;
    //虚线循环之间的宽度
    final space = (dashSpace + dashWidth);

    //虚线显示
    while (startX < max) {
      for (var i = 0; i < 5; i++) {
        canvas.drawLine(Offset(startX, (i + 1) * 224 / 5),
            Offset(startX + dashWidth, (i + 1) * 224 / 5), paint);
      }
      startX += space;
    }

    ///初始值
    var startOffset = 20.5 - 16;

    ///Y轴
    for (int i = 0; i < 5; i++) {
      //绘制文字
      var textPainter = TextPainter(
        text: TextSpan(
            text: "${(((((maxWeight + 20) / 100).ceil()) * 100) / 4) * i}",
            style: TextStyle(
                color: Color.fromRGBO(153, 153, 153, 1), fontSize: 12)),
        textDirection: TextDirection.rtl,
      )..layout();
      textPainter.paint(canvas, Offset(startOffset, ((5 - i) * (224 / 5)) - 7));
    }
  }

  ///是否进行界面的重新刷新加载
  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

//画布X坐标轴
class MyPainterY extends CustomPainter {
  MyPainterY(this.getRecordLists, this.context, this.mm);

  ///获取接口数据
  List<GetRecordLists> getRecordLists;
  BuildContext context;
  int mm;

  ///初始化折线坐标列表
  List<Offset> points = [];

  ///初始化起始坐标
  double startX;

  ///初始化两个画布
  var path1 = Path();
  var path = Path();

  ///初始值
  var startOffset;

  ///初始化折线图的X,Y坐标
  var brokenLineX, brokenLineY;

  ///初始化背景颜色
  var gradient;

  ///初始化折线点
  var brokenLine = Paint();

  ///渐变色的点
  var _paint2 = Paint();

  ///绘制圆点
  var _paints = Paint();
  var _paints2 = Paint();

  ///初始化赋值
  init() {
    //初始化起始坐标
    startX = 37.5;
    //初始值
    startOffset = 20.5 - 16;
    //折线的X,Y轴
    brokenLineX = ((MediaQuery.of(context).size.width - 50 - 2) / 5);
    brokenLineY = ((((224 / 5) * 5) - (224 / 5)) / 100);
    //初始化折线点
    brokenLine
      ..strokeWidth = 1.5
      ..isAntiAlias = true // 是否抗锯齿
      ..style = PaintingStyle.stroke
      ..color = Color.fromRGBO(255, 64, 89, 1);

    //初始化背景颜色
    gradient = new LinearGradient(
      begin: Alignment.topCenter,
      end: Alignment.bottomCenter,
      colors: [
        Color.fromRGBO(255, 64, 89, 1),
        Color.fromRGBO(255, 255, 255, 0.5)
      ],
    );
    //渐变色的点
    _paint2
      ..strokeWidth = 1.5
      ..isAntiAlias = true
      ..color = Colors.red;
    //绘制圆点
    _paints
      ..strokeWidth = 1.5
      ..isAntiAlias = true
      ..style = PaintingStyle.stroke
      ..color = Color.fromRGBO(255, 64, 89, 1);
    _paints2
      ..strokeWidth = 1.5
      ..isAntiAlias = true
      ..color = Colors.white;
  }

  @override
  void paint(Canvas canvas, Size size) {
    ///调用初始化数据
    init();

    ///X轴
    for (int i = getRecordLists.length - 1; i >= 0; i--) {
      ///绘制X轴的文字显示
      List<String> zz = getRecordLists[i].dateTime.split("-");
      // 字符串截取
      // if(zz[1].startsWith("0")){
      //   zz[1]=zz[1].substring(1, 2);
      // }
      //绘制文字
      var textPainter = TextPainter(
        text: TextSpan(
            text: "${zz[1]}.${zz[2]}",
            style: TextStyle(
                color: Color.fromRGBO(153, 153, 153, 1), fontSize: 12)),
        textDirection: TextDirection.rtl,
      )..layout();

      ///X轴
      textPainter.paint(
          canvas,
          Offset(
              (((MediaQuery.of(context).size.width - 50 - 18) / 5) *
                  (getRecordLists.length - i - 1)),
              5 * (224 / 5) + 22));

      /// 绘制折线显示
      if (i == getRecordLists.length - 1) {
        path1.moveTo((brokenLineX * (getRecordLists.length - i - 1)) + 12,
            224 - (brokenLineY * (getRecordLists[i].weight)));
      } else {
        path1.lineTo((brokenLineX * (getRecordLists.length - i - 1)) + 12,
            224 - (brokenLineY * (getRecordLists[i].weight)));
      }

      ///绘制圆点
      points.add(Offset((brokenLineX * (getRecordLists.length - i - 1)) + 12,
          224 - (brokenLineY * (getRecordLists[i].weight))));

      ///绘制背景图片
      if (i == getRecordLists.length - 1) {
        path.moveTo(12, 5 * (224 / 5) + 22);
        path.lineTo(12, 224 - (brokenLineY * (getRecordLists[i].weight)));
      } else if (i == 0) {
        path.lineTo((brokenLineX * (getRecordLists.length - 0 - 1)) + 12,
            224 - (brokenLineY * (getRecordLists[i].weight)));
        path.lineTo((brokenLineX * (getRecordLists.length - 0 - 1)) + 12,
            5 * (224 / 5) + 22);
      } else {
        path.lineTo((brokenLineX * (getRecordLists.length - i - 1)) + 12,
            224 - (brokenLineY * (getRecordLists[i].weight)));
      }
    }
    canvas.drawPath(path1, brokenLine);

    ///绘制背景色渐变
    final rect =
        new Rect.fromLTWH(0.0, 0.0, size.width, size.height - 20); //设置开始和结束位置
    _paint2.shader = gradient.createShader(rect);
    canvas.drawPath(path, _paint2);

    ///绘制圆点
    for (int i = 0; i < points.length; i++) {
      canvas.drawCircle(points[i], 3.0, _paints2 //绘画风格改为stroke
          );
      canvas.drawCircle(points[i], 3.0, _paints //绘画风格改为stroke
          );
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

//点击的坐标
class MyChangeY extends CustomPainter {
  MyChangeY(this.getRecordLists, this.context, this.mm);

  ///获取接口数据
  List<GetRecordLists> getRecordLists;
  BuildContext context;
  int mm;

  ///初始化折线坐标列表
  List<Offset> points = [];

  @override
  void paint(Canvas canvas, Size size) {
    ///绘制圆点
    //圆点
    var _paints = Paint()
      ..strokeWidth = 1.5
      ..isAntiAlias = true // 是否抗锯齿
      ..color = Color.fromRGBO(255, 64, 89, 1);
    //圆点
    var _paints2 = Paint()
      ..strokeWidth = 1.5
      ..isAntiAlias = true // 是否抗锯齿
      ..style = PaintingStyle.stroke
      ..color = Colors.white;

    //X轴的初始值
    double changeX = (((MediaQuery.of(context).size.width - 50 - 2) / 5) *
            (getRecordLists.length - mm - 1)) +
        12;

    //X轴的初始值
    double changeY = 224 -
        (((((224 / 5) * 5) - (224 / 5)) / 100) * (getRecordLists[mm].weight));

    //虚线之间的宽度
    var dashWidth = 5;
    var dashSpace = 5;
    //虚线循环之间的宽度
    final space = (dashSpace + dashWidth);
    var starY = 224 / 5;

    //虚线显示
    while (starY <= ((224 / 5) * 5)) {
      for (var i = 0; i < 5; i++) {
        canvas.drawLine(Offset(changeX, starY),
            Offset(changeX, starY + dashWidth), _paints);
      }
      starY += space;
    }

    ///绘制圆点
    points.add(Offset(changeX, changeY));
    canvas.drawCircle(points[0], 3.0, _paints2 //绘画风格改为stroke
        );
    canvas.drawCircle(points[0], 3.0, _paints //绘画风格改为stroke
        );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}
